package com.learn.spring.async.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.text.MessageFormat;
import java.util.concurrent.Executor;

/**
 * 自定义线程池继承AsyncConfigurerSupport
 *
 * @author cong zhi
 * @email 448341911@qq.com
 * @createDate 2023/3/20 17:18
 * @version: v1.0
 */
@Slf4j
@Configuration
public class SpringAsyncConfigurer extends AsyncConfigurerSupport {

    @Bean
    public ThreadPoolTaskExecutor asyncExecutor() {
        // spring封装的一个线程池
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // 随便写一些配置
        threadPool.setCorePoolSize(10);
        threadPool.setMaxPoolSize(30);
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        threadPool.setAwaitTerminationSeconds(60 * 15);
        return threadPool;
    }


    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error(MessageFormat.format("Exception in async method:{}  error:{} ", method.getName(), ex.getMessage()));
    }
}

